﻿using System;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.LIB;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class LaySTraps : HYExternalCommand
	{
		public override Result HYExecute(ref string tranName)
		{
			tranName = "布置s弯";
			FamilySymbol settedFamilySymbol = HYDrainageSystemSetting.Instance.GetSettedFamilySymbol(base.Doc, HYFamilySymbolSign.SBend);
			ISelectionFilter selectionFilter = new RiserPipeFilter();
			foreach (Element element in base.Sel.PickElementsByRectangle(selectionFilter, "请框选立管").ToList<Element>())
			{
				YJKPiping<Pipe> hypiping = new YJKPiping<Pipe>((Pipe)element);
				Connector connector;
				if (hypiping.StartConnector.Connector.CoordinateSystem.BasisZ.IsAlmostEqualTo(-XYZ.BasisZ))
				{
					connector = hypiping.StartConnector.Connector;
				}
				else
				{
					connector = hypiping.EndConnector.Connector;
				}
				Level level;
				double elevation;
				if (base.Doc.ActiveView.GenLevel != null)
				{
					level = base.Doc.ActiveView.GenLevel;
					elevation = level.Elevation;
				}
				else
				{
					level = YJKRevitTools.GetLevelClose(connector.Origin, base.Doc);
					elevation = level.Elevation;
				}
				FamilyInstance familyInstance = YJKRevitTools.LayFamilySymbol(base.Doc, connector.Origin, settedFamilySymbol, level, 0.0);
				string text = "";
				YJKRevitTools.SetFamilyInstanceOffSet(familyInstance, level, connector.Origin.Z - elevation);
				YJKRevitTools.SetFamilyInstanceDiameter(familyInstance, NumbericTools.feetTomm(connector.Radius * 2.0), ref text);
				YJKRevitTools.ConnectTwoElement(familyInstance, hypiping.Piping);
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
